/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package as24gc.remote;

import as24gc.db.DBIntegrationFunction;
import as24gc.db.Dealers;
import as24gc.db.Vehicles;
import as24gc.parser.InputObject;
import as24gc.parser.ParserUtility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author nico.vassallo
 */
public class Receiver extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("start");
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {


            //processInput
            String inContent = this.processInput(request);


            // parsing and validation xml
            // assign xml to object
            InputObject inputObject = ParserUtility.runEngineParserSax(inContent);
            System.out.println("action: " + inputObject.getAction());
            
            Vehicles inVehicle = inputObject.getV();
            if (inVehicle.getNid() <= 0) {
                System.out.println("missing input nid: "+inVehicle.getNid());
                throw new ServletException("[001]INPUT_VALIDATION: missing input nid");
            }

            DBIntegrationFunction dbIntegrationFanction = new DBIntegrationFunction();

            //query dealrid in input
            //check user and password
            Dealers inDealer = dbIntegrationFanction.getDealers(inVehicle.getDealers().getId());
            if (inDealer.getUser().equals(inVehicle.getDealers().getUser())
                    && inDealer.getPassword().equals(inVehicle.getDealers().getPassword())) {
                //valid credential
            } else {
                //invalid credential
                throw new IOException("Credential User and Password Exception");
            }

            

            //compare input (nid, dealerid) as database(nid, dealerid)
            //create for new
            //else update for existing
            // set db.vehicles.uptdated to 1
            Vehicles storedVehicle = dbIntegrationFanction.getVehiclesByNidAndDealerId(inVehicle.getNid(), inVehicle.getDealers().getId());
            inVehicle.setUpdated(DBIntegrationFunction.UPDATED);


            //Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"));
            //Date dateCal = cal.getTime();


            Date date = new Date();
            System.out.println("date: " + date);
            if (storedVehicle == null) {
                // add
                System.out.println("adding...");
                inVehicle.setDateCreate(date);
                int res = dbIntegrationFanction.storeVehicles(inVehicle);
                System.out.println("stored new Vehicles: " + res);
            } else if (inputObject.getAction().contains("edit")){
                //update
                System.out.println("updating...");
                inVehicle.setId(storedVehicle.getId());
                inVehicle.setDateLastupdate(date);
                inVehicle.setDateCreate(storedVehicle.getDateCreate());
                dbIntegrationFanction.updateVehicles(inVehicle);
                System.out.println("updateVehicles");
            }else if (inputObject.getAction().contains("delete")){
                //update
                System.out.println("delete...");
                inVehicle.setId(storedVehicle.getId());
                dbIntegrationFanction.deleteVehicles(inVehicle);
                System.out.println("deleteVehicles");
            }



        } finally {
            //out.println("end");
            out.close();
            System.out.println("end");
        }
    }

    private String processInput(HttpServletRequest request) throws IOException {

        InputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        String linea = reader.readLine();

        String inContent = "";
        while (linea != null) {
            inContent = inContent + linea;
            linea = reader.readLine();
        }
        System.out.println("inContent: " + inContent);
        return inContent;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);

    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
